package com.css.crm.exception;

import java.util.Iterator;

import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;

import org.apache.log4j.Logger;

import com.css.crm.utility.ConstantUtil;

/**
 * Exception Handler to handle view expired exception
 */
/*
 * Log Date Name Description 0024746 2013 JAN 23 isaac.so.t.h Creation
 */
public class ViewExpiredExceptionExceptionHandler extends ExceptionHandlerWrapper {

	private static final Logger log = Logger.getLogger(ViewExpiredExceptionExceptionHandler.class);
	private ExceptionHandler wrapped;

	public ViewExpiredExceptionExceptionHandler(ExceptionHandler wrapped) {
		this.wrapped = wrapped;
	}

	@Override
	public ExceptionHandler getWrapped() {
		return this.wrapped;
	}

	/**
	 * Redirect to login page when view expired
	 */
	/*
	 * Log Date Name Description 0024746 2013 JAN 23 isaac.so.t.h Creation
	 */
	@Override
	public void handle() throws FacesException {
		for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
			ExceptionQueuedEvent event = i.next();
			ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
			Throwable t = context.getException();
			if (t instanceof ViewExpiredException) {
				FacesContext fc = FacesContext.getCurrentInstance();
				NavigationHandler nav = fc.getApplication().getNavigationHandler();
				try {
					log.info("Handle ViewExpiredException");
					nav.handleNavigation(fc, null, ConstantUtil.PAGE_LOGIN);
					fc.renderResponse();
				} finally {
					i.remove();
				}
			}
		}
		getWrapped().handle();
	}

}
